const asarUtil = require('../../common/utils/asarUtil');
const pkgUtil = require('../../common/utils/pkgUtil');
const uuidUtil = require('../../common/utils/uuidUtil');
const pluginInfoDAO = require('../../core/rdsService/pluginInfoDAO');

const { updatePluginFeatureByPluginModel } = require('./updatePluginFeature')



exports.installPackage = function (path) {
    process.noAsar = false
    const pkg = pkgUtil.getPkgByAsarPath(path)
    const groupId = pkg.groupId
    const artifactId = pkg.artifactId
    const version = pkg.version
    const private = pkg.private
    const preloadPath = pkg.preload


    pluginInfoDAO.getPluginInfoByCondition(null, groupId, artifactId, (thePlugins) => {
        let thePlugin = null
        if (thePlugins.length > 0) {
            thePlugin = thePlugins[0]
            asarUtil.removePackage(thePlugin.pluginId)
            thePlugin.version = version
            if (JSON.stringify(pkg) != JSON.stringify(thePlugin.pluginInfo)) {
                thePlugin.pluginInfo = pkg
                pluginInfoDAO.update(thePlugin)
            }
        } else {
            const uuid = uuidUtil.uuid()
            thePlugin = pluginInfoDAO.composeModel(uuid, groupId, artifactId, version, private, pkg)
            pluginInfoDAO.insert(thePlugin)
        }

        asarUtil.movePackage(path, thePlugin.pluginId, () => {
            asarUtil.extractPackage(thePlugin.pluginId)

        })
        updatePluginFeatureByPluginModel(thePlugin)

    })


}
